﻿Imports System.IO


''' <summary>
''' Allows sequential access to the tokens within a raw file
''' </summary>
''' <remarks></remarks>
Public Class RawReader
    Implements IDisposable

#Region "IDisposable Support"
    Private disposedValue As Boolean ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: dispose managed state (managed objects).
            End If

            mData = Nothing
        End If
        Me.disposedValue = True
    End Sub

    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

    Private mData As String
    Private mPosition As Integer

    Private Sub New()
    End Sub

    Public Sub New(fileName As String)
        Dim reader As New StreamReader(fileName)

        mData = reader.ReadToEnd

        reader.Close()
        reader.Dispose()

        mPosition = 0
    End Sub

    Public Shared Function FromString(text As String) As RawReader
        Dim ret As New RawReader

        ret.mData = text
        ret.mPosition = 0

        Return ret
    End Function


    Public Function ReadNextToken() As Boolean
        If mPosition >= mData.Length - 1 Then
            Return False
        Else
            Dim startIndex As Integer = 0
            Dim endIndex As Integer = 0

            startIndex = mData.IndexOf("["c, mPosition)
            If startIndex > -1 Then
                endIndex = mData.IndexOf("]"c, startIndex)
                If endIndex > -1 Then
                    Dim part As String = mData.Substring(startIndex, endIndex - startIndex + 1)
                    mToken = Token.Parse(part, Nothing)
                    mPosition = endIndex + 1

                    Dim commentEnd As Integer = mData.IndexOf("[", mPosition)
                    Dim length As Integer = commentEnd - mPosition
                    If length > 0 Then
                        Dim comment As String = mData.Substring(mPosition, length).Trim
                        If comment > "" Then
                            mToken.Comment = comment
                        End If
                        mPosition = commentEnd
                    End If

                    Return True
                Else
                    Return False
                End If
            Else
                Return False
            End If
        End If
    End Function

    Private mToken As Token
    Public ReadOnly Property CurrentToken As Token
        Get
            Return mToken
        End Get
    End Property

End Class
